//
//  TransitionAnimation.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/7/28.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "TransitionAnimation.h"
#import "ThumbnailListNavigationController.h"
#import "ThumbnailListViewController.h"
#import "AssetPageViewController.h"
#import "AssetItemViewController.h"

@implementation TransitionAnimation

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.35f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIView *containerView           = [transitionContext containerView];
    containerView.backgroundColor   = [UIColor blackColor];
    
    if (self.isPositiveAnimation)
    {
        ThumbnailListNavigationController *fromVC = (ThumbnailListNavigationController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        ThumbnailListViewController *listVC = (ThumbnailListViewController *)fromVC.topViewController;
        AssetPageViewController *toVC = (AssetPageViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        AssetItemViewController *itemVC = (AssetItemViewController *)toVC.viewControllers.firstObject;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toVC.pageIndex inSection:0];
        
        UIView *cellView = [listVC.collectionView cellForItemAtIndexPath:indexPath];
        cellView.hidden = YES;
        UIImageView *imageView = [itemVC imageViewInAssetView];
        UIView *snapshot = [self resizedSnapshot:imageView ViewController:toVC];
        
        // Find the scales of snapshot
        float startScale = MAX(cellView.frame.size.width / snapshot.frame.size.width,
                                  cellView.frame.size.height / snapshot.frame.size.height);
        
        CGPoint cellCenter = [fromVC.view convertPoint:cellView.center fromView:cellView.superview];
        CGPoint snapCenter = CGPointMake(toVC.view.center.x, MAX(toVC.view.center.y, snapshot.bounds.size.height / 2));
        
        // Find the bounds of the snapshot mask
        float width         = snapshot.bounds.size.width;
        float height        = snapshot.bounds.size.height;
        float length        = MIN(width, height);
        
        CGRect startBounds  = CGRectMake((width-length)/2, (height-length)/2, length, length);
        
        // Create the mask
        UIView *mask            = [[UIView alloc] initWithFrame:startBounds];
        mask.backgroundColor    = [UIColor blackColor];
        
        // Prepare transition
        snapshot.transform  = CGAffineTransformMakeScale(startScale, startScale);;
        snapshot.layer.mask = mask.layer;
        snapshot.center     = cellCenter;
        
        toVC.view.frame     = [transitionContext finalFrameForViewController:toVC];
        toVC.view.alpha     = 0;
        
        // Add to container view
        [containerView addSubview:toVC.view];
        [containerView addSubview:snapshot];
        
        // Animate
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
             usingSpringWithDamping:0.75
              initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             fromVC.view.alpha          = 0;
                             snapshot.transform         = CGAffineTransformMakeScale(1.0f, 1.0f);
                             snapshot.layer.mask.bounds = snapshot.bounds;
                             snapshot.center            = snapCenter;
                         }
                         completion:^(BOOL finished){
                             toVC.view.alpha   = 1;
                             cellView.hidden = NO;
                             [snapshot removeFromSuperview];
                             [transitionContext completeTransition:YES];
                         }];
    } else {
        ThumbnailListNavigationController *toVC = (ThumbnailListNavigationController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        ThumbnailListViewController *listVC = (ThumbnailListViewController *)toVC.topViewController;
        AssetPageViewController *fromVC = (AssetPageViewController *)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
        AssetItemViewController *itemVC = (AssetItemViewController *)fromVC.viewControllers.firstObject;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:fromVC.pageIndex inSection:0];
        
        toVC.view.frame         = [transitionContext finalFrameForViewController:toVC];
        toVC.view.alpha         = 0;
        fromVC.view.alpha       = 0;
        
        UIView *cellView        = [listVC.collectionView cellForItemAtIndexPath:indexPath];
        cellView.hidden = YES;
        
        // 当cellview的frame为零或者超出屏幕frame时，重新布局collectionView
        if (CGRectEqualToRect(cellView.frame, CGRectZero)) {
            [listVC.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            [listVC.collectionView layoutIfNeeded];
            
            cellView = [listVC.collectionView cellForItemAtIndexPath:indexPath];
            cellView.hidden = YES;
        } else {
            CGRect rect = CGRectMake(listVC.collectionView.bounds.origin.x,
                                     listVC.collectionView.bounds.origin.y + listVC.collectionView.contentInset.top,
                                     listVC.collectionView.bounds.size.width,
                                     listVC.collectionView.bounds.size.height - listVC.collectionView.contentInset.top);
            
            if (cellView.frame.origin.y < rect.origin.y) {
                CGPoint point = CGPointMake(listVC.collectionView.contentOffset.x,
                                            listVC.collectionView.contentOffset.y - (rect.origin.y - cellView.frame.origin.y));
                
                [listVC.collectionView setContentOffset:point];
            } else if (cellView.frame.origin.y + cellView.frame.size.height > rect.origin.y + rect.size.height) {
                CGPoint point = CGPointMake(listVC.collectionView.contentOffset.x,
                            listVC.collectionView.contentOffset.y + (cellView.frame.origin.y + cellView.frame.size.height) - (rect.origin.y + rect.size.height));
                
                [listVC.collectionView setContentOffset:point];
            }
        }
        
        UIImageView *imageView  = [itemVC imageViewInAssetView];
        UIView *snapshot        = [self resizedSnapshot:imageView ViewController:fromVC];
        
        CGPoint cellCenter  = [toVC.view convertPoint:cellView.center fromView:cellView.superview];
        CGPoint snapCenter  = fromVC.view.center;
        
        // Find the scales of snapshot
        float endScale      = MAX(cellView.frame.size.width / snapshot.frame.size.width,
                                  cellView.frame.size.height / snapshot.frame.size.height);
        
        // Find the bounds of the snapshot mask
        float width         = snapshot.bounds.size.width;
        float height        = snapshot.bounds.size.height;
        float length        = MIN(width, height);
        CGRect endBounds    = CGRectMake((width-length)/2, (height-length)/2, length, length);
        
        UIView *mask            = [[UIView alloc] initWithFrame:snapshot.bounds];
        mask.backgroundColor    = [UIColor whiteColor];
        
        // Prepare transition
        snapshot.layer.mask     = mask.layer;
        snapshot.center         = snapCenter;
        
        // Add to container view
        [containerView addSubview:toVC.view];
        [containerView addSubview:snapshot];
        
        // Animate
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
                              delay:0
             usingSpringWithDamping:1
              initialSpringVelocity:0
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
                             toVC.view.alpha            = 1;
                             snapshot.transform         = CGAffineTransformMakeScale(endScale, endScale);
                             snapshot.layer.mask.bounds = endBounds;
                             snapshot.center            = cellCenter;
                         }
                         completion:^(BOOL finished){
                             [snapshot removeFromSuperview];
                             cellView.hidden = NO;
                             [transitionContext completeTransition:YES];
                         }];
    }
}

#pragma mark - Snapshot

- (UIView *)resizedSnapshot:(UIImageView *)imageView ViewController:(AssetPageViewController *)VC
{
    AssetItemViewController *itemView = VC.viewControllers.firstObject;
    
    // 以固定竖屏的方式取值width、height
    float width = MIN(VC.view.bounds.size.width, VC.view.bounds.size.height);
    float height = MAX(VC.view.bounds.size.width, VC.view.bounds.size.height);
    
    CGSize size;
    if ([itemView isVideo]) {
        float scale = MIN(width / imageView.image.size.width, height / imageView.image.size.height);
        size = CGSizeMake(imageView.image.size.width * scale, imageView.image.size.height * scale);
    } else {
        float scale = (int)((width/imageView.bounds.size.width) *1000) / 1000.0f;
        size = CGSizeMake(imageView.bounds.size.width * scale, imageView.bounds.size.height * scale);
    }
    
    UIGraphicsBeginImageContextWithOptions(size, YES, 0);
    
    [[UIColor blackColor] set];
    UIRectFill(CGRectMake(0, 0, size.width, size.height));
    
    [imageView.image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *resized = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return (UIView *)[[UIImageView alloc] initWithImage:resized];
}

@end
